import { getCloudbaseContext } from '@cloudbase/node-sdk';
import { i18n } from './i18n';
import { isString } from './string';
import { ScfEnvContext, ScfParamContext } from './types';
import { extractErrorMessage } from './typescript';

/**
 * `getCloudbaseContext` 的类型推断扩展
 *
 * `const { envName } = getEnvContext<{ envName?: string }>(context);`
 *
 * @param ctx
 */
export const getEnvContext = <MixIn extends Record<string, unknown> = Record<string, unknown>>(
  ctx: ScfParamContext,
): ScfEnvContext<MixIn> => getCloudbaseContext(ctx) as ScfEnvContext<MixIn>;

export type ScfReturn<T extends Record<string, unknown>> = {
  success: boolean;
  msg?: string | null;
  data?: T | null;
};

export const scfReturn = <T extends Record<string, unknown> = Record<string, unknown>>(
  success: Error | unknown | boolean,
  msg?: string | null,
  data?: T | null,
): ScfReturn<T> => {
  if (success instanceof Error) {
    return { success: false, msg: msg || extractErrorMessage(success) || i18n('unknownError'), data };
  }
  return { success: !!success, msg, data };
};

export const scfSuccess = <T extends Record<string, unknown> = Record<string, unknown>>(
  msg?: string | null,
  data?: T | null,
): ScfReturn<T> => scfReturn(true, msg, data);

export const scfFail = <T extends Record<string, unknown> = Record<string, unknown>>(
  msg?: Error | unknown | string | null,
  data?: T | null,
): ScfReturn<T> => {
  if (msg instanceof Error) {
    return scfReturn(msg, null, data);
  }
  return scfReturn(false, isString(msg) ? msg : undefined, data);
};
